package com.example.experiment4;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class BroadcastActivity extends AppCompatActivity {
    NetworkChangeReceiver netChangeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast);

        // 网络状态变化广播
        IntentFilter netConnIntentFilter = new IntentFilter();
        netConnIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        netChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(netChangeReceiver, netConnIntentFilter);

        // 电量变化广播
        Intent batteryIntent = getApplicationContext().registerReceiver(null,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int currLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int total = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
        int percent = currLevel * 100 / total;
        Log.i("BatteryChangeReceiver", "battery: " + percent + "%");

        // 自定义广播
        Intent intent = new Intent("pers.cnzdy.mobilerookie.USER_DEFINED_BROADCAST");
        sendBroadcast(intent);
        sendOrderedBroadcast(intent, null);

        // 本地广播
        LocalReceiver localReceiver = new LocalReceiver();
        LocalBroadcastManager localBroadcastManager =
                LocalBroadcastManager.getInstance(this);
        IntentFilter localIntentFilter = new IntentFilter(
                "pers.cnzdy.mobilerookie.LOCAL_BROADCAST");
        localBroadcastManager.registerReceiver(localReceiver, localIntentFilter);

        Intent intentLocal = new Intent("pers.cnzdy.mobilerookie.LOCAL_BROADCAST");
        localBroadcastManager.sendBroadcast(intentLocal);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (netChangeReceiver != null)
            unregisterReceiver(netChangeReceiver);

//        if (messageReceiver != null)
//            unregisterReceiver(messageReceiver);
    }

}
